<template>
  <div class="rechargeRuleSetting-activity">
    <el-table-form ref="form" :model="query">
      <el-form-item label="规则生效时间" prop="date">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="适用机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择适用机构',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="规则状态" prop="reguStatus">
        <el-select v-model="query.reguStatus" clearable>
          <el-option label="禁用" value="1" />
          <el-option label="已启用" value="2" />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      header-row-class-name="table-row-name"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />

    <activityDialog ref="activityDialogRef" :tree-data="treeData" @refresh="search" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { rechargeRuleList, rechargeRuleChangeStatus, rechargeRuleDelete } from '@/api'
  import { mapGetters } from 'vuex'
  import activityDialog from './ActivityDialog.vue'
  export default {
    components: {
      activityDialog
    },
    data() {
      return {
        treeData: [],
        query: {
          orgSNNo: '', // 适用机构orgSNNo
          date: [], // 规则生效时间
          reguStatus: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        actionColWidth: 80
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'reguId',
            label: '规则编号',
            width: 120
          },
          {
            prop: 'remark',
            label: '规则描述',
            width: 150
          },
          {
            prop: 'beginDt',
            label: '规则生效开始时间',
            width: 200,
            render: (h, { row }) => (
            <span>{row.beginDt && moment(row.beginDt).format('YYYY-MM-DD')}</span>
          )
          },
          {
            prop: 'endDt',
            label: '规则生效结束时间',
            width: 200,
            render: (h, { row }) => (
            <span>{row.endDt && moment(row.endDt).format('YYYY-MM-DD')}</span>
          )
          },

          {
            prop: 'orgName',
            label: '适用机构',
            width: 200
          },
          {
            prop: 'reguStatus',
            label: '状态',
            width: 150,
            render: (h, { row }) => <span>{this.getReguStatusText(row.reguStatus)}</span>
          },

          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                {row.reguStatus === 1 && (
                  <el-link
                    size='mini'
                    underline={false}
                    onClick={() => this.update(row, $index)}
                  >
                    编辑
                  </el-link>
                )}

                <el-link size='mini' underline={false} onClick={() => this.detali(row)}>
                  规则详情
                </el-link>

                {row.reguStatus === 1 ? (
                  <el-link
                    size='mini'
                    underline={false}
                    onClick={() => this.changeStatus(row, 2)}
                  >
                    启用
                  </el-link>
                ) : (
                  <el-link
                    size='mini'
                    underline={false}
                    onClick={() => this.changeStatus(row, 1)}
                  >
                    禁用
                  </el-link>
                )}

                {row.reguStatus === 1 && (
                  <el-link
                    size='mini'
                    underline={false}
                    type='danger'
                    onClick={() => this.del(row, $index)}
                  >
                    删除
                  </el-link>
                )}
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData()
    },

    methods: {
      // 获取适用机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择适用机构
      selectTreeChange(value) {
        this.query.orgSNNo = value.orgSNNo
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.date && this.query.date.length > 0) {
          query[`beginDt`] = moment(this.query.date[0]).format()
          query[`endDt`] = moment(this.query.date[1]).format()
        }
        delete query.date

        const { status, data } = await rechargeRuleList(query)
        if (status === 200) {
          this.tableData.data = data.rows
          if (currentPage === 1) this.tableData.total = data.total
          this.flexColumnWidth()
        }
      },
      // 处理表格状态数据
      getReguStatusText(val) {
        switch (val) {
        case 1:
          return '禁用'
        case 2:
          return '已启用'
        }
      },
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新建
      add() {
        this.$refs['activityDialogRef'].show(1)
      },
      // 编辑
      update(row) {
        this.$refs['activityDialogRef'].show(2, row)
      },
      // 规则详情
      detali(row) {
        this.$refs['activityDialogRef'].show(3, row)
      },
      // 修改规则状态  1禁用 2启用
      changeStatus(row, type) {
        this.$confirm(`确认要执行此操作吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.changeStatusSubmit(row, type)
        })
      },
      async changeStatusSubmit(row, type) {
        const params = {
          reguStatus: type, // 规则描述
          rcType: 1, // 规则类型
          orgId: row.orgId, // 机构id
          orgSNNo: row.orgSNNo, // 适用机构编号
          orgName: row.orgName, // 适用机构名称
          reguId: row.reguId // 规则id
        }

        const { status } = await rechargeRuleChangeStatus(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `${type === 1 ? '禁用' : '启用'}规则成功`,
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      // 删除
      del(row) {
        this.$confirm(`确定要删除该规则吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.delSubmit(row)
        })
      },
      async delSubmit(row) {
        const params = {
          reguId: row.reguId // 规则id
        }
        const { status } = await rechargeRuleDelete(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: `删除规则成功`,
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      }
    }
  }
</script>

<style lang="scss" scoped></style>
